package com.zx.controller;

import com.zx.common.ResponseCode;
import com.zx.entity.Link;
import com.zx.entity.User;
import com.zx.repository.LinkRepository;
import com.zx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/link")
public class LinkController {
    @Autowired
    private LinkRepository linkRepository;
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "0") Integer page,
                             @RequestParam(value = "size", defaultValue = "3") Integer size,
                             Map<String,Object> map){
        PageRequest request = PageRequest.of(page,size);
        Page<Link> link = linkRepository.findAll(request);
        map.put("link",link);
        return new ModelAndView("link/list");
    }
    //添加链接
    @GetMapping("/addLink")
    public ModelAndView addlink(){
        return new ModelAndView("link/addLink");
    }
    @PostMapping("/saveLink")
    public ModelAndView savelink(Link link,
                                 Map<String,Object> map){
        linkRepository.save(link);
        map.put("msg", ResponseCode.SAVE_SUCCESS.getDesc());
        map.put("url","/foodshare/link/list");
        return new ModelAndView("common/success",map);
    }
    //删除公告
    @GetMapping("/delete/{linkId}")
    public ModelAndView delete(@PathVariable("linkId") Integer id,
                               Map<String,Object> map){
        Link link = linkRepository.getOne(id);
        linkRepository.delete(link);
        map.put("msg",ResponseCode.DELETE_SUCCESS.getDesc());
        map.put("url","/foodshare/link/list");
        return new ModelAndView("common/success",map);
    }
    //编辑公告
    @GetMapping("/list/{linkId}")
    public ModelAndView EditUser(@PathVariable("linkId") Integer id,
                                 Map<String,Object> map){
        Link link = linkRepository.getOne(id);
        map.put("link",link);
        return new ModelAndView("link/editLink",map);
    }

}
